package first.niuke.simple;

import java.util.ArrayList;

/**
 * @ClassName NC38
 * @description:
 * @author: 荣燊
 * @create: 2021-06-10 09:54
 **/
public class NC38 {
    public static void main(String[] args) {
        int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
//        int[][] a = {{2, 3}};
        for(int b : spiralOrder(a)) {
            System.out.print(b);
        }

    }

    private static ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> list = new ArrayList<Integer>();

        if (matrix.length == 0) {
            return list;
        }

        int left = 0, right = matrix[0].length-1;
        int low = 0, high = matrix.length-1;
        int total = (right+1)*(high+1); //这个total真实灵魂所在啊，cao

        while(left <= right && low <= high) {
            int i = left;
            while (i <= right && total > 0) {
                list.add(matrix[low][i++]);
                --total;
            }
            ++low;

            int j = low;
            while (j <= high && total > 0) {
                list.add(matrix[j++][right]);
                --total;
            }
            --right;

            int m = right;
            while(m >= left && total > 0) {
                list.add(matrix[high][m--]);
                --total;
            }
            --high;

            int n = high;
            while (n >= low && total > 0) {
                list.add(matrix[n--][left]);
                --total;
            }
            ++left;
        }
        return list;
    }
}
